<template>
  <el-card header="设备端账户密码登录">
    <el-form label-position="left" label-width="120px" inline>
      <el-form-item label="账户">
        <el-input v-model="form.username" />
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" />
      </el-form-item>
      <el-form-item label="设备编码">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleLogin">登陆</el-button>
      </el-form-item>
    </el-form>
    <div inline v-if="userToken">
      <div>
        用户TOKEN : {{ userToken }}
      </div>
      <div v-if="sessionToken">
        会话TOKEN : {{ sessionToken }}
        <el-button type="text" icon="el-icon-refresh" @click="deviceLogin" />
      </div>
      <div v-if="device.code">
        设备信息 : {{ device.name }}
      </div>
    </div>
  </el-card>
</template>
<script>
  import request from "@/utils/request";
  import {
    removeToken,
    setToken
  } from '@/utils/auth'
  export default {
    name: 'DeviceLoginCard',
    data() {
      return {
        form: {
          username: 'TEST',
          password: '123456',
          roleId: 4,
          code: 'IoT-Locker-Test002'
        },
        userToken: null,
        sessionToken: null,
        device: {}
      }
    },
    methods: {
      handleLogin() {
        const vm = this
        removeToken()
        request({
          method: "post",
          url: "/device/login/user",
          data: this.form,
        }).then(res => {
          vm.userToken = res.userToken
          vm.deviceLogin()
        })
      },
      deviceLogin() {
        const vm = this
        removeToken()
        request({
          method: 'post',
          url: '/device/login/device',
          data: `code=${this.form.code}&token=${this.userToken}`,
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
        }).then(res => {
          vm.sessionToken = res.data
          const {
            sessionToken
          } = vm
          setToken(sessionToken)
          vm.deviceInfo()
        })
      },
      deviceInfo() {
        const vm = this
        request({
          method: 'get',
          url: '/device/device/code',
        }).then(res => {
          const {
            userToken,
            sessionToken
          } = vm
          vm.device = Object.assign({}, res.data)
          vm.$emit('logined', {
            userToken,
            sessionToken,
            device: res.data
          })
        })
      }
    }
  }

</script>
